﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace DIProject.Sales
{
    public partial class PartiesList :System.Windows.Forms.Form// Form
    {
        public PartiesList()
        {
            InitializeComponent();
        }
        private void InitAll()
        {
            ComboBox cb = cbDepartments.ComboBox;            
            DataSets.UtilTableAdapters.UtilQueries adpt = new DIProject.DataSets.UtilTableAdapters.UtilQueries();
            Int32? curDept = adpt.CurrentDepartment();
            DataSets.Util.DepartmentsDataTable data = null;
            DataSets.UtilTableAdapters.DepartmentsTableAdapter dAdapt = new DIProject.DataSets.UtilTableAdapters.DepartmentsTableAdapter();
            data = dAdapt.GetData();
            DataSets.Util.DepartmentsRow dr = data.NewDepartmentsRow();
            dr.Id = -100;
            dr.Name = "По всем подразделениям";
            data.Rows.InsertAt(dr, 0);
            cb.ValueMember = "Id";
            cb.DisplayMember = "Name";
            cb.DataSource = data;
            /*if (curDept.HasValue)
                cb.SelectedValue = curDept.Value;*/
            if (curDept.HasValue)
            {
                // this.currentPartyTableAdapter.Fill(this.util.CurrentParty, curDept.Value, 0);
                Data.Party.PopulatePartyTable(this.util.CurrentParty, curDept.Value, 0);
                curDeptCashe = curDept.Value;
            }
            else
                //this.currentPartyTableAdapter.Fill(this.util.CurrentParty, -100, 0);
                Data.Party.PopulatePartyTable(this.util.CurrentParty, -100, 0);
            lblSummApt.Text = GetSum2();
        }
        private void PartiesList_Load(object sender, EventArgs e)
        {
            InitAll();
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            currentPartyBindingSource.Filter = "FullName LIKE '*" + txbFilter.Text + "*'";
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            currentPartyBindingSource.Filter = string.Empty;
        }

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
                return;
            DataRowView drv = dataGridView1.Rows[e.RowIndex].DataBoundItem as DataRowView;
            DataSets.Util.CurrentPartyRow pr = drv.Row as DataSets.Util.CurrentPartyRow;
            PartyesDetail pd = new PartyesDetail(pr.Id);
            pd.MdiParent = this.MdiParent;
            pd.Show();
        }
        private string GetSumm()
        {
            DataSets.UtilTableAdapters.UtilQueries adapter = new DIProject.DataSets.UtilTableAdapters.UtilQueries();
            decimal? d = adapter.AllPartySumm();
            if (d.HasValue)
            {
                return d.Value.ToString();
            }
            return string.Empty;
        }
        private string GetSum2()
        {
            decimal sum = 0;
            foreach (DataGridViewRow r in this.dataGridView1.Rows)
            {
                DataRowView drv = r.DataBoundItem as DataRowView;
                if (drv != null)
                {
                    DataSets.Util.CurrentPartyRow pr = drv.Row as DataSets.Util.CurrentPartyRow;
                    sum += pr.RestQntty * pr.RetailPrice;
                }
            }
            return sum.ToString();
        }

        private void btnRefreshSumm_Click(object sender, EventArgs e)
        {
            Refresh1();
        }
        Int32 curDeptCashe = -100;
        bool IsLoad = true;
        private void cbDepartments_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (IsLoad)
            {
                IsLoad = false;
                return;
            }
            Refresh1();
        }
        private void Refresh1()
        {
            Int32 minusDey;
            if (!Int32.TryParse(txbDeys.Text, out minusDey))
            {
                MessageBox.Show("Введите целое цисло");
                txbDeys.Focus();
                return;
            }
            currentPartyBindingSource.Filter = string.Empty;
            ComboBox cb = cbDepartments.ComboBox;
            Int32 curDept = (Int32)cb.SelectedValue;
           // this.currentPartyTableAdapter.Fill(this.util.CurrentParty, curDept, minusDey);
            Data.Party.PopulatePartyTable(this.util.CurrentParty, curDept, minusDey);
            curDeptCashe = curDept;
            lblSummApt.Text = GetSum2();
        }
        private void txbFilter_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                currentPartyBindingSource.Filter = "FullName LIKE '*" + txbFilter.Text + "*'";
            }
        }

        private void txbDeys_Validating(object sender, CancelEventArgs e)
        {
            string tmp = txbDeys.Text;
            if (string.IsNullOrEmpty(tmp))
            {
                txbDeys.Text = "0";
                e.Cancel = false;
                return;
            }
            Int32 ParserMinusDey;
            if (Int32.TryParse(tmp, out ParserMinusDey))
            {
                e.Cancel = false;
            }
            else
            {
                MessageBox.Show("Введите целое цисло");
                e.Cancel = true;
                txbDeys.Focus();
                return;
            }
        }
        
        private XmlNode CreateXML(List<Int32> partyIDs)
        {
            if (partyIDs.Count < 1)
                throw new Util.DIException("Ошибка! Нужно выбрать одну или несколько строк!");
            XmlDocument doc = new XmlDocument();
            XmlElement root = doc.CreateElement("r");
            doc.AppendChild(root);
            foreach (Int32 i in partyIDs)
            {
                XmlElement item = doc.CreateElement("i");
                XmlAttribute val = doc.CreateAttribute("v");
                val.InnerText = i.ToString();
                item.Attributes.Append(val);
                root.AppendChild(item);
            }
            return doc;
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            List<Int32> partyIDs = new List<int>();
            
            if (dataGridView1.SelectedRows == null) return;
            if (dataGridView1.SelectedRows.Count <= 0) return;
            try
            {
                foreach (DataGridViewRow dgvr in dataGridView1.SelectedRows)
                {
                    partyIDs.Add(Convert.ToInt32(dgvr.Cells["PartyIdColumn"].Value));
                }
                string str = CreateXML(partyIDs).OuterXml;
                ReceptionGoods.ZennikOnly szForm = new ReceptionGoods.ZennikOnly(CreateXML(partyIDs).OuterXml);
                szForm.Show();
            }
            catch { }            
        }

        private void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows == null)
                toolStripButton3.Enabled = false;
            else
                if (dataGridView1.SelectedRows.Count <= 0)
                    toolStripButton3.Enabled = false;
                else
                    toolStripButton3.Enabled = true;


        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            Util.SettingFile sf = Util.Setting2.GetSetting();
            switch (sf.BarcodePrinter)
            {
                case DIProject.Util.BarCodePrinterType.BZB:
                    ShtrihProcess();
                    break;
                case DIProject.Util.BarCodePrinterType.ZEBRA:
                    ZebraShtrihProcess();
                    break;
                default:
                    ErrorPrintBarCode();
                    break;
            }
        }
        private void ErrorPrintBarCode()
        {
            MessageBox.Show("Не задан принтер штрихэтикеток");
        }
        private void ZebraShtrihProcess()
        {
            /*
            ///печатаем все с количеством указанном в количестве            
            if (cbSelRows.SelectedIndex == 0)
            {
                foreach (DataGridViewRow row in dgvPartiesList.Rows)
                {
                    DataRowView dvr = row.DataBoundItem as DataRowView;
                    DataSets.waybillsData.SZDataDetailRow dr = dvr.Row as DataSets.waybillsData.SZDataDetailRow;
                    string price = dr.RetailPrice.ToString();
                    //Util.StrihWapper.PrintBarKode(30, 20, dr.RestQntty, 1, KString(dr.FullName), price, "Arial", dr.BarCode);
                    Util.StrihWapper.ZebraPrintBarcode(dr.RestQntty, KString(dr.FullName), price, dr.BarCode);
                }
            }
            ///печатаем выделенные с диалогом по каждой отдельно
            else
            {
                if (dgvPartiesList.SelectedRows.Count < 1)
                {
                    MessageBox.Show("Необходимо выбрать хотя бы 1 партию", "Выберите партию", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                foreach (DataGridViewRow row in dgvPartiesList.SelectedRows)
                {
                    DataRowView dvr = row.DataBoundItem as DataRowView;
                    DataSets.waybillsData.SZDataDetailRow dr = dvr.Row as DataSets.waybillsData.SZDataDetailRow;
                    ShtrihInfo si = new ShtrihInfo(dr);
                    si.ShowDialog(this);
                    DialogResult dro = si.DialogResult;
                    if (dro == DialogResult.OK)
                    {
                        if (si.Count == 0)
                        {
                            si.Close();
                            continue;
                        }
                        string price = dr.RetailPrice.ToString();
                        // Util.StrihWapper.PrintBarKode(30, 20, si.Count, 1, KString(dr.FullName), price, "Arial", dr.BarCode);
                        Util.StrihWapper.ZebraPrintBarcode(si.Count, KString(dr.FullName), price, dr.BarCode);
                    }
                    si.Close();
                }
            }*/
        }
        /// <summary>
        /// печатаем штрихэтикетки
        /// </summary>
        private void ShtrihProcess()
        {
            /*
            ///печатаем все с колличеством указанном в количестве
            if (cbSelRows.SelectedIndex == 0)
            {
                foreach (DataGridViewRow row in dgvPartiesList.Rows)
                {
                    DataRowView dvr = row.DataBoundItem as DataRowView;
                    DataSets.waybillsData.SZDataDetailRow dr = dvr.Row as DataSets.waybillsData.SZDataDetailRow;
                    string price = dr.RetailPrice.ToString();
                    Util.StrihWapper.PrintBarKode(30, 20, dr.RestQntty, 1, KString(dr.FullName), price, "Arial", dr.BarCode);
                }
            }
            ///печатаем выделенные с диологом по каждой отдельно
            else
            {
                if (dgvPartiesList.SelectedRows.Count < 1)
                {
                    MessageBox.Show("Необходимо выбрать хотябы 1 партию", "Выберите партию", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                foreach (DataGridViewRow row in dgvPartiesList.SelectedRows)
                {
                    DataRowView dvr = row.DataBoundItem as DataRowView;
                    DataSets.waybillsData.SZDataDetailRow dr = dvr.Row as DataSets.waybillsData.SZDataDetailRow;
                    ShtrihInfo si = new ShtrihInfo(dr);
                    si.ShowDialog(this);
                    DialogResult dro = si.DialogResult;
                    if (dro == DialogResult.OK)
                    {
                        if (si.Count == 0)
                        {
                            si.Close();
                            continue;
                        }
                        string price = dr.RetailPrice.ToString();
                        Util.StrihWapper.PrintBarKode(30, 20, si.Count, 1, KString(dr.FullName), price, "Arial", dr.BarCode);
                    }
                    si.Close();
                }
            }*/
        }
        private string KString(string s)
        {
            if (s.Length < 50)
                return s;
            return s.Substring(0, 50);
        }
    }
}